#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/input.h>

static int event0_fd = -1;
struct input_event ev0[64];

/*
		x 		y
code 		0		1
value		    delt [-,0,+]
type			2

#define EV_SYN 0x00
#define EV_KEY 0x01
#define EV_REL 0x02
#define EV_ABS 0x03
#define EV_MSC 0x04
#define EV_SW 0x05
#define EV_LED 0x11
#define EV_SND 0x12
#define EV_REP 0x14
#define EV_FF 0x15
#define EV_PWR 0x16
#define EV_FF_STATUS 0x17
#define EV_MAX 0x1f

EV_SYN 0x00 同步事件
EV_KEY 0x01 按键事件，如KEY_VOLUMEDOWN
EV_REL 0x02 相对坐标,   如shubiao上报的坐标
EV_ABS 0x03 绝对坐标，如触摸屏上报的坐标
EV_MSC 0x04 其它
EV_LED 0x11 LED
EV_SND 0x12 声音
EV_REP 0x14 Repeat
EV_FF 0x15 力反馈 
~~~~~~~~~~~~~~~~~~~~~~~~
EV_PWR       电源
EV_FF_STATUS   状态

#define REL_X 0x00
#define REL_Y 0x01
#define REL_Z 0x02
#define REL_RX 0x03
#define REL_RY 0x04
#define REL_RZ 0x05
#define REL_HWHEEL 0x06
#define REL_DIAL 0x07
#define REL_WHEEL 0x08
#define REL_MISC 0x09
#define REL_MAX 0x0f

*/

const char* evType2Str[] = {
	[EV_SYN] = "EV_SYN",
	[EV_KEY] = "EV_KEY",
	[EV_REL] = "EV_REL",
	[EV_ABS] = "EV_ABS",
	[EV_MSC] = "EV_MSC",
	[EV_SW] = "EV_SW",
	[EV_LED] = "EV_LED",
	[EV_SND] = "EV_SND",
	[EV_REP] = "EV_REP",

	[EV_FF] = "EV_FF",
	[EV_PWR] = "EV_PWR",

	[EV_FF_STATUS] = "EV_FF_STATUS",
	[EV_MAX] = "EV_MAX",
};
static int realx=0,realy=0;
//for handling event0, mouse/key/ts
static int handle_event0() {
    int button = 0, i, rd;

    rd = read(event0_fd, ev0, sizeof(struct input_event) * 64);
    if ( rd < sizeof(struct input_event) ) return 0;

    for (i = 0; i < rd / sizeof(struct input_event); i++) {
        //printf("type:%d, code:%d, value:%d\n", ev0[i].type, ev0[i].code, ev0[i].value);
	if (ev0[i].type == EV_REL){
		if(ev0[i].code == REL_X){
			realx += ev0[i].value;
		}else{
			realy += ev0[i].value;
		}
	}
        else if (ev0[i].type == EV_ABS){
		if(ev0[i].code == REL_X){
			realx = ev0[i].value;
		}else{
			realy = ev0[i].value;
		}
	}
        else if (ev0[i].type == EV_KEY) {
            if (ev0[i].code == 158) {
                //if key esc then exit
                return 0;
            }
        } else if (ev0[i].type == 0 && ev0[i].code == 0 && ev0[i].value == 0) {
            //realx = 0, realy = 0;
        }
	if(realx<0) realx=0; if(realx>1920) realx=1920;
	if(realy<0) realy=0; if(realy>1080) realy=1080;
        printf("event(%d): type: %s; code: %3d; value: %3d; realx: %3d; realy: %3d\n", i,
   evType2Str[ev0[i].type], ev0[i].code, ev0[i].value, realx, realy);
    }

    return 1;
}

int main(void) {

    int fd = ashmem_create_region("SharedRegionName", 1024); 

 int done = 1;
    printf("sizeof(struct input_event) = %d\n", sizeof(struct input_event));

    event0_fd = open("/dev/input/event2", O_RDWR);

    if ( event0_fd < 0 )
        return -1;

    while ( done ) {
  printf("begin handel_event0...\n");
        done = handle_event0();
  printf("end handel_event0...\n");
    }

    if ( event0_fd > 0 ) {
        close(event0_fd);
        event0_fd = -1;
    }

    return 0;

}
